import time
from datetime import datetime, timedelta
from . import admin_blue
from flask import request, render_template, jsonify, session, g, current_app, redirect, abort, url_for
from info import constants, db
from info.models import Category, News, User
from info.utils.common import verify_login
from info.utils.image_storage import storage
from info.utils.response_code import RET, error_map


# 首页视图函数
@admin_blue.route("/")
@verify_login
def admin_index():
    user = g.user
    return render_template("admin/index.html", user=user.to_dict())


# 登录视图函数
@admin_blue.route("/login", methods=["GET", "POST"])
def admin_login():
    """登录视图函数
    1.判断是什么请求
    2.获取参数
    3.进行校验判断
    4.登录成功后存入ad用户的session并重定向到后台主页
    """
    if request.method == "GET":
        # 取session中取指定的值
        # 从session中该用户的数据,默认为空
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)

        # 如果用户id存在,并且是管理员,那么直接跳转管理后台主页
        if user_id and is_admin:
            return redirect(url_for("admin.admin_index"))

        return render_template("admin/login.html")

    # 登录校验
    username = request.form.get("username")
    password = request.form.get("password")

    # 判断是否为空
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as a:
        current_app.logger.error(a)
        return render_template("admin/login.html", errms=error_map.get(RET.DBERR))

    # 如果查询出来的用户为空
    if not user and not user.check_password(password):
        return render_template("admin/login.html", errmsg="用户名或者密码错误")

    # 如果不是ad用户
    if not user.is_admin:
        return render_template("admin/login.html", errmsg="权限不足")

    # 往session中存入该用户的数据
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True

    # 登录成功后重定向到后台主页
    return redirect(url_for("admin.admin_index"))


# 用户统计
@admin_blue.route("/user_count")
def user_count():
    """
    月新增数:获取到本月第一天0点0分0秒的时间对象,然后查询最后一次登录比其大的所有数据
    日新增数:获取到当日0点0分0秒的是时间对象,然后查询最后一次登录比其大的所有数据
    图表查询:遍历查询数据每一天的数据(当前天数,减去某些天)
    :return:
    """
    # 1.查询总人数
    total_count = 0

    try:  # 查询所有普通用户
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as a:
        current_app.logger.error(a)

    # 2.根据月时间查询月新增数
    mon_count = 0
    now = time.localtime()
    try:
        # 月开始时间
        mon_begin = "%d-%02d-01" % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, "%Y-%m-%d")
        mon_count = total_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_date).count()

    except Exception as b:
        current_app.logger.error(b)

    # 3.根据日新增数查询日新增数
    day_count = 0
    try:
        day_begin = "%d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, "%Y-%m-%d")
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()

    except Exception as c:
        current_app.logger.error(c)

    # 4.查询图表信息
    # 获取到当天00:00:00时间
    today_begin = "%d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)

    now_date = datetime.strptime(today_begin, "%Y-%m-%d")

    # 定义空数据组,保存数据
    active_date = []
    active_count = []

    # 依次添加数据,再反转
    for i in range(31):
        begin_date = now_date - timedelta(days=i)
        end_date = now_date - timedelta(days=(i - 1))
        active_date.append(begin_date.strftime("%Y-%m-%d"))

        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.create_time >= begin_date,
                                      User.create_time < end_date).count()

        except Exception as d:
            current_app.logger.error(d)
        active_count.append(count)

    # 反转列表
    active_date.reverse()  # 一天的
    active_count.reverse()  # 一个月的

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_date": active_date,
        "active_count": active_count
    }
    return render_template("admin/user_count.html", data=data)


# 新闻列表
@admin_blue.route("/user_list")
def user_list():
    """获取用户列表"""

    # 获取地址栏的参数
    page = request.args.get("p", 1)

    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1

    # 设置变量默认值
    users = []
    current_page = 1
    total_page = 1

    # 查询数据
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,
                                                                                                       constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                                       False)

        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as b:
        current_app.logger.error(b)

    # 返回数据
    users_list = []
    for user in users:
        users_list.append(user.to_admin_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "users": users_list
    }
    return render_template("admin/user_list.html", data=data)


@admin_blue.route("/news_review")
def news_review():
    """返回待审核新闻列表"""

    # 获取地址栏的参数
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", "")

    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1

    # 设置变量默认值
    filters = [News.status != 0]
    users = []
    current_page = 1
    total_page = 1

    # 关键字参数不为空
    if keywords:
        filters.append(News.title.contains(keywords))

    # 查询数据
    news_list = None
    try:
        paginate = News.query.filter(News.title.contains(keywords)).order_by(News.create_time.desc()).paginate(page,
                                                                                                               constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                               False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as b:
        current_app.logger.error(b)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_dict_list
    }

    return render_template("admin/news_review.html", data=data)


# 新闻审核详情
@admin_blue.route("/news_review_detail", methods=["GET", "POST"])
def news_review_detail():
    """新闻审核
    1.获取参数
    2.判断参数
    3.根据新闻id查询
    4.判断状态设置状态值
    5.保存状态并且返回结果
    """
    # 1.GET请求获取参数
    if request.method == "GET":
        # 获取参数新闻id
        news_id = request.args.get("news_id")

        # 查询新闻
        news = News.query.get(news_id)

        data = {
            "news": news.to_dict()
        }
        return render_template("admin/news_review_detail.html", data=data)

    # 1.POST请求,获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.判断参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3.查询新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as a:
        current_app.logger.error(a)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    # 4.如果当前新闻等于accept表示新闻审核通过
    if action == "accept":
        news.status = 0
    else:
        # 获取到拒绝通过的理由
        reason = request.json.get("reason")

        # 拒绝理由
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="请输入拒绝的理由")

        # 设置拒绝的理由并且把状态设置为-1表示没有通过
        news.status = -1
        news.reason = reason

    # 5.保存数据
    try:
        db.session.commit()
    except Exception as b:
        current_app.logger.error(b)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK))


# 新闻编辑
@admin_blue.route("/news_edit")
def news_edit():
    """返回新闻列表"""

    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", "")

    try:
        page = int(page)
    except Exception as a:
        current_app.logger.error(a)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    try:
        filters = []

        # 如果有关键词
        if keywords:
            # 添加关键词的检所选项
            filters.append(News.title.contains(keywords))

        # 分页查询
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as b:
        current_app.logger.error(b)

    # 返回数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_dict_list
    }
    return render_template("admin/news_edit.html", data=data)


# 新闻编辑详情
@admin_blue.route("/news_edit_detail", methods=["POST", "GET"])
def news_edit_detail():
    """新闻编辑详情"""
    # 获取参数
    if request.method == "GET":
        news_id = request.args.get("news_id")
        news = News.query.get(news_id)

        if not news_id and not news:
            return render_template("admin/news_edit_detail.html", data={"errmsg": "参数不够"})

        # 查询分类的数据
        categories = Category.query.all()
        categories_li = []
        for category in categories:
            c_dict = category.to_dict()
            c_dict["is_selected"] = True

            if category.id == news.category_id:
                c_dict["is_selected"] = True
            categories_li.append(c_dict)

        categories_li.pop(0)

        data = {
            "news": news.to_dict(),
            "categories": categories_li
        }
        return render_template("admin/news_edit_detail.html", data=data)

    # POST请求
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 1.1判断数据是否有值
    if not all([title, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as a:
        current_app.logger.error(a)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据") \
 \
    # 1.2读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as b:
            current_app.logger.error(b)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 2.上传图片
        try:
            key = storage(index_image)
        except Exception as c:
            current_app.logger.error(c)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    # 3.设置相关数据
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    # 4.保存到数据库
    try:
        db.session.commit()
    except Exception as d:
        current_app.logger.error(d)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 5.返回结果
    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK))


# 新闻分类
@admin_blue.route("/news_category")
def news_category():
    """新闻分类"""
    # 获取所有的分类数据
    categories = Category.query.all()

    # 定义列表保存分类数据
    categories_dicts = []

    for category in categories:
        cate_dict = category.to_dict()
        categories_dicts.append(cate_dict)

    categories_dicts.pop(0)

    # 返回数据
    return render_template("admin/news_type.html", data={"categories": categories_dicts})


# 添加/修改
@admin_blue.route("/add_category", methods=["POST"])
def add_category():
    """添加或者修改视图"""
    category_id = request.json.get("id")
    category_name = request.json.get("name")

    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 判断是否有分类id
    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as a:
            current_app.logger.error(a)
            return jsonify(errno=RET.DBERR, errmsg=error_map.get(RET.DBERR))

        if not category:
            return jsonify(errno=RET.NODATA, errmsg="未查询到分类信息")

        category.name = category_name

    else:
        # 如果没有分类id,则是添加分类
        category = Category()
        category.name = category_name
        db.session.add(category)

    try:
        db.session.commit()
    except Exception as b:
        current_app.logger.error(b)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK))
